package com.tom.zx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tom.zx.entity.FurnishOrder;
import com.tom.zx.entity.User;
import com.tom.zx.service.IFurnishOrderService;
import com.tom.zx.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;

/**
 * 装修订单 前端控制器
 *
 * @author lp
 * @since 2022-05-16
 */
@RestController
@RequestMapping("/zx/furnishOrder")
@AllArgsConstructor
public class FurnishOrderController {

  private final IFurnishOrderService furnishOrderService;

  private final IUserService userService;

  /** 查询分页列表 */
  @GetMapping("/page")
  public Page<FurnishOrder> loadPageFurnishOrder(
      Principal principal, Page<FurnishOrder> page, FurnishOrder furnishOrder) {
    final String name = principal.getName();
    final User user = userService.loadUserByUserName(name);
    return furnishOrderService.page(
        page,
        new LambdaQueryWrapper<FurnishOrder>()
            .like(FurnishOrder::getOrderNumber, furnishOrder.getOrderNumber())
            .eq(FurnishOrder::getUserId, user.getId()));
  }

  /** 保存订单信息 */
  @PostMapping
  public boolean saveFurnishOrder(Principal principal, @RequestBody FurnishOrder furnishOrder) {
    final String userName = principal.getName();
    final User user = userService.loadUserByUserName(userName);
    return furnishOrderService.saveOrUpdate(furnishOrder);
  }

  /** 删除数据 通过ids */
  @DeleteMapping
  public boolean deleteFurnishOrderByIds(@RequestBody Long[] ids) {
    return furnishOrderService.removeBatchByIds(Arrays.asList(ids));
  }

  @PutMapping("{id}/status")
  public void changeStatus(@PathVariable Long id) {
    final FurnishOrder furnishOrder = new FurnishOrder();
    furnishOrder.setId(id);
    furnishOrder.setStatus(1);
    furnishOrderService.updateById(furnishOrder);
  }
}
